using Fabric.Internal;
using Fabric.Internal.Crashlytics;
using Fabric.Runtime;
//using Facebook.Unity;
using GameAnalyticsSDK;
using mixpanel;
using mixpanel.detail;
//using PresageLib;
using System;
using System.Collections;
using System.Collections.Generic;
//using TapjoyUnity.Internal;
using UnityEngine;
using UnityEngine.Purchasing;
using Voodoo.Sauce.Internal.Ads;
using Voodoo.Sauce.Internal.Analytics;
using Voodoo.Sauce.Internal.AppRater;
using Voodoo.Sauce.Internal.CrossPromo;
using Voodoo.Sauce.Internal.GDPR;
using Voodoo.Sauce.Internal.IAP;
using Voodoo.Sauce.Internal.Misc;

namespace Voodoo.Sauce.Internal
{
	internal class VoodooSauceBehaviour : MonoBehaviour
	{
		private const string TAG = "VoodooSauceBehaviour";

		private static VoodooSauceBehaviour _instance;

		[SerializeField]
		private mixpanel.Mixpanel _mixpanelPrefab;

		[SerializeField]
		private GameAnalytics _gameAnalyticsPrefab;

		//[SerializeField]
	//	private TapjoyComponent _tapjoyPrefab;

		[SerializeField]
		private FabricInit _fabricPrefab;

		[SerializeField]
		private CrashlyticsInit _crashlyticsPrefab;

		[SerializeField]
		private Voodoo.Sauce.Internal.AppRater.AppRater _appRaterPrefab;

		[SerializeField]
		private GameObject _voodooGdprCanvas;

		[SerializeField]
		private CohortDebugMenu _cohortDebugMenuPrefab;

		[SerializeField]
		private GameObject _bannerBackgroundPrefab;

		private CohortDebugMenu _cohortDebugMenu;

		private VoodooSettings _settings;

		public static Action OnInternetConnect;

		private void Awake()
		{
			if (base.transform != base.transform.root)
			{
				throw new Exception("VoodooSauce prefab HAS to be at the ROOT level!");
			}
			_settings = Resources.Load<VoodooSettings>("VoodooSettings");
			VoodooLog.SetLogLevel(_settings.VoodooLogLevelInEditor);
			if (_instance != null)
			{
				VoodooLog.LogW("VoodooSauceBehaviour", "VoodooSauce is already initialized! Please avoid creating multiple instance of VoodooSauce. This object will be destroyed: " + base.gameObject.name);
				UnityEngine.Object.Destroy(base.gameObject);
				return;
			}
			_instance = this;
			UnityEngine.Object.DontDestroyOnLoad(this);
			if (_settings == null)
			{
				throw new Exception("Can't find VoodooSauce settings file. Please check you have created the file using Assets/Create/VoodooSauce/Settings File");
			}
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing VoodooSauce v3.4.0b4 on " + _instance.name);
			base.gameObject.AddComponent<ExponentialBackoff>();
			UnityEngine.Object.Instantiate(_bannerBackgroundPrefab);
			InitAbTest();
			InitAppRater();
			InitGdpr(OnConsentGiven, OnConsentUpdated);
		}

		private void Start()
		{
			List<ProductDescriptor> list = new List<ProductDescriptor>(_settings.Products);
			if (!string.IsNullOrEmpty(_settings.NoAdsBundleId))
			{
				//list.Add(new ProductDescriptor(_settings.NoAdsBundleId, ProductType.NonConsumable, 2.99f));
			}
			//VoodooIAP.Init(list.ToArray());
			StartCoroutine(CheckInternetAvailability());
		}

		private void OnConsentGiven(VoodooGDPR.GdprConsent gdpr)
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Consent has been given: " + gdpr);
			if (gdpr.ExplicitConsentGivenForAnalytics || !gdpr.IsGdprApplicable)
			{
				InitFabric();
				InitGameAnalytics();
				InitFacebook();
			}
			InitMixpanel();
			InitAnalytics(gdpr.ExplicitConsentGivenForAnalytics || !gdpr.IsGdprApplicable);
			InitCrossPromo();
			if (!gdpr.IsEmbargoedCountry)
			{
				InitVoodooAds(gdpr.ExplicitConsentGivenForAds || !gdpr.IsGdprApplicable);
			}
		}

		private void OnConsentUpdated(VoodooGDPR.GdprConsent gdpr)
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Consent has been updated: " + gdpr);
			VoodooAnalytics.SetConsent(gdpr.ExplicitConsentGivenForAnalytics);
			VoodooAds.SetConsent(gdpr.ExplicitConsentGivenForAds);
		}

		private void InitAbTest()
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing AB Tests");
			VoodooAnalytics.InitializeAbTest(_settings.RunningABTests, _settings.MixpanelUsersPercentPerCohort, _settings.DebugForcedCohort);
		}

		private void InitAnalytics(bool consent)
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing Analytics");
			VoodooAnalytics.InitializeAnalytics(consent);
		}

		private void InitGdpr(Action<VoodooGDPR.GdprConsent> onConsentGiven, Action<VoodooGDPR.GdprConsent> onConsentUpdated)
		{
			if (_voodooGdprCanvas == null)
			{
				throw new Exception("No GDPR Canvas, please make sure the Voodoo Gdpr Canvas is set in the VoodooSauce prefab");
			}
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing GDPR");
			base.gameObject.AddComponent<Requests>();
			VoodooGDPR.SetCallbacks(onConsentGiven, onConsentUpdated);
			UnityEngine.Object.Instantiate(_voodooGdprCanvas);
		}

		private void InitAppRater()
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing AppRater-RateBox");
			UnityEngine.Object.Instantiate(_appRaterPrefab);
			Voodoo.Sauce.Internal.AppRater.AppRater.Initialize(_settings.AppleStoreId, Application.identifier, _settings.AppRaterDelayAfterLaunchInSeconds, _settings.AppRaterPostponeCooldownInSeconds, _settings.AppRaterMinimumNumberOfGamesPlayed);
		}

		private void InitFabric()
		{
			VoodooLog.Log("VoodooSauceBehaviour", "FabricPrefabs: " + _fabricPrefab + " - " + _crashlyticsPrefab);
			if (_fabricPrefab != null && _crashlyticsPrefab != null)
			{
				VoodooLog.Log("VoodooSauceBehaviour", "Initializing Fabric");
				Fabric.Runtime.Fabric.Initialize();
				FabricInit fabricInit = UnityEngine.Object.Instantiate(_fabricPrefab);
				fabricInit.name = "FabricInit";
				CrashlyticsInit crashlyticsInit = UnityEngine.Object.Instantiate(_crashlyticsPrefab);
				crashlyticsInit.name = "CrashlyticsInit";
			}
		}

		private void InitMixpanel()
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing Mixpanel");
			mixpanel.Mixpanel mixpanel = UnityEngine.Object.FindObjectOfType<mixpanel.Mixpanel>();
			if (mixpanel == null)
			{
				if (!string.IsNullOrEmpty(_settings.MixpanelProdToken) && VoodooAnalytics.PlayerIsInACohort())
				{
					mixpanel = UnityEngine.Object.Instantiate(_mixpanelPrefab);
					mixpanel.token = _settings.MixpanelProdToken;
					mixpanel.debugToken = _settings.MixpanelProdToken;
					mixpanel.trackInEditor = true;
					//mixpanel.minLogLevel = mixpanel.detail.Mixpanel.LogEntry.Level.LL_WARNING;
					mixpanel.flushInterval = 1;
					mixpanel.gameObject.SetActive(value: true);
				}
				else
				{
					VoodooLog.LogW("VoodooSauceBehaviour", "No tokens for Mixpanel has been set, Mixpanel will be disabled.");
				}
			//	MixpanelWrapper.Initialize(mixpanel != null);
				return;
			}
			throw new Exception("Looks like Mixpanel has been added manually to the scene, please remove your Mixpanel object and let VoodooSauce handle it.");
		}

		private void InitGameAnalytics()
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing GameAnalytics");
			bool flag = !_settings.GameAnalyticsAndroidGameKey.Equals(string.Empty) && !_settings.GameAnalyticsAndroidSecretKey.Equals(string.Empty);
			GameAnalytics x = UnityEngine.Object.FindObjectOfType<GameAnalytics>();
			if (x == null)
			{
				x = UnityEngine.Object.Instantiate(_gameAnalyticsPrefab);
				AddOrUpdatePlatform(RuntimePlatform.IPhonePlayer, _settings.GameAnalyticsIosGameKey, _settings.GameAnalyticsIosSecretKey);
				if (flag)
				{
					AddOrUpdatePlatform(RuntimePlatform.Android, _settings.GameAnalyticsAndroidGameKey, _settings.GameAnalyticsAndroidSecretKey);
				}
				else
				{
					RemovePlatform(RuntimePlatform.Android);
				}
				GameAnalytics.SettingsGA.InfoLogBuild = false;
				GameAnalytics.SettingsGA.InfoLogEditor = false;
				x.gameObject.SetActive(value: true);
				GameAnalytics.Initialize();
				return;
			}
			throw new Exception("Looks like GameAnalytics has been added manually to the scene. please remove your GameAnalytics object and let VoodooSauce handle it.");
		}

		private void AddOrUpdatePlatform(RuntimePlatform platform, string gameKey, string secretKey)
		{
			if (!GameAnalytics.SettingsGA.Platforms.Contains(platform))
			{
				GameAnalytics.SettingsGA.AddPlatform(platform);
			}
			int index = GameAnalytics.SettingsGA.Platforms.IndexOf(platform);
			GameAnalytics.SettingsGA.UpdateGameKey(index, gameKey);
			GameAnalytics.SettingsGA.UpdateSecretKey(index, secretKey);
			GameAnalytics.SettingsGA.Build[index] = Application.version;
		}

		private void RemovePlatform(RuntimePlatform platform)
		{
			if (GameAnalytics.SettingsGA.Platforms.Contains(platform))
			{
				int index = GameAnalytics.SettingsGA.Platforms.IndexOf(platform);
				GameAnalytics.SettingsGA.RemovePlatformAtIndex(index);
			}
		}

		private void InitFacebook()
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing Facebook");
			//FB.Init(delegate
			//{
			//	VoodooLog.Log("VoodooSauceBehaviour", "Facebook Initialized");
			//});
		}

		private void InitCrossPromo()
		{
			if (_settings.EnableCrossPromo)
			{
				VoodooLog.Log("VoodooSauceBehaviour", "Initializing Cross Promotion...");
				VoodooCrossPromo.Init();
			}
		}

		private void InitVoodooAds(bool consent)
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing VoodooAds");
			AdUnits androidAdUnits = _settings.AndroidAdUnits;
			InitOgury(consent);
			VoodooAds.Init(androidAdUnits);
			InitTapjoy(consent);
			VoodooAds.InitializeMopub();
		}

		private void InitOgury(bool consent)
		{
			if (!string.IsNullOrEmpty(_settings.OguryAndroidAppKey))
			{
				VoodooLog.Log("VoodooSauceBehaviour", "Initializing Ogury");
				//Presage.Initialize(_settings.OguryAndroidAppKey);
				VoodooLog.Log("VoodooSauceBehaviour", "Initializing Ogury: Done");
			}
		}

		private void InitTapjoy(bool consent)
		{
			VoodooLog.Log("VoodooSauceBehaviour", "Initializing Tapjoy");
			//TapjoySettings tapjoySettings = ScriptableObject.CreateInstance<TapjoySettings>();
			//tapjoySettings.AndroidSettings.DisableAdvertisingId = !consent;
			//tapjoySettings.AndroidSettings.DisablePersistentIds = !consent;
			//tapjoySettings.AndroidSettings.SdkKey = _settings.TapjoyAndroidSdkKey;
			////TapjoyComponent tapjoyComponent = UnityEngine.Object.Instantiate(_tapjoyPrefab);
			//tapjoyComponent.settings = tapjoySettings;
			//tapjoyComponent.name = "TapjoyUnity";
			//tapjoyComponent.gameObject.SetActive(value: true);
		}

		public static void ShowCohortDebugMenu()
		{
			if (!(_instance == null))
			{
				VoodooLog.Log("VoodooSauceBehaviour", "Showing Cohort Debug Menu");
				if (_instance._cohortDebugMenu == null)
				{
					_instance._cohortDebugMenu = UnityEngine.Object.Instantiate(_instance._cohortDebugMenuPrefab);
				}
				else
				{
					_instance._cohortDebugMenu.Show();
				}
			}
		}

		public static void CloseCohortDebugMenu()
		{
			if (!(_instance == null) && !(_instance._cohortDebugMenu == null))
			{
				_instance._cohortDebugMenu.Hide();
			}
		}

		private IEnumerator CheckInternetAvailability()
		{
			NetworkReachability reachability = Application.internetReachability;
			while (true)
			{
				if (reachability != Application.internetReachability)
				{
					reachability = Application.internetReachability;
					if (reachability != 0 && OnInternetConnect != null)
					{
						OnInternetConnect();
					}
				}
				yield return new WaitForSecondsRealtime(1f);
			}
		}

		private void OnApplicationPause(bool pauseStatus)
		{
			if (!pauseStatus)
			{
				//TenjinWrapper.Connect();
			}
		}

		internal static void InvokeAfter(Action methodToCall, float duration)
		{
			_instance.StartCoroutine(_instance.InvokeAfterCoroutine(methodToCall, duration));
		}

		internal static void InvokeCoroutine(IEnumerator coroutine)
		{
			_instance.StartCoroutine(coroutine);
		}

		private IEnumerator InvokeAfterCoroutine(Action methodToCall, float duration)
		{
			yield return new WaitForSeconds(duration);
			methodToCall();
		}
	}
}
